<template>
  <view class="my-settle-container">
     <!-- 全选区域 -->
      <label class="radio" @click="changeAllState">
        <radio color="#C00000" :checked="isFullCheck" /><text>全选</text>
      </label>

      <!-- 合计区域 -->
      <view class="amount-box">
        合计:<text class="amount">￥{{totalPrice}}</text>
      </view>
      
      <!-- 结算区域 -->
      <view class="btn-settle" @click="settlement">结算({{totalAmount}})</view>
  </view>
</template>

<script>
  import { mapGetters, mapMutations, mapState } from 'vuex'
  
  export default {
    name:"my-settle",
    data() {
      return {
        seconds: 3
      };
    },
    computed: {
      ...mapGetters('m_cart', ['isFullCheck', 'totalPrice', 'totalAmount']), // 购物车模块
      ...mapGetters('m_user', ['addstr']), // 用户信息模块
      ...mapState('m_user', ['token']), // 用户token
      ...mapState('m_cart', ['cart']), // 购物车
    },
    methods: {
      ...mapMutations('m_cart', ['updateGoodsAllState']),
      ...mapMutations('m_user', ['updateRedirectInfo']),
      // 修改所有购物车商品的选中状态
      changeAllState(){
        this.updateGoodsAllState(!this.isFullCheck)
      },
      settlement(e){
        console.log('结算条件判断开始')
        // 1 至少选择一件商品 
        if(this.totalAmount === 0) return uni.$showMsg('请至少选择一件商品！')
        
        // 2 是否选择了收获地址 
        if(!this.addstr) return uni.$showMsg('请选择收获地址')
        
        // 3 是否登录（token）
        if(!this.token) return this.delayNavigate()
        
        // 4 准备支付
        this.payOrder()
        
        console.log('可以交钱了')
      },
      
      delayNavigate(){
        // 为登录的话，倒计时提示用户
        console.log('准备倒计时')
        for(let i = 0; i<=this.seconds; i++){
          setTimeout(() => {
            if(i === 3){
              uni.switchTab({
                url: '/pages/my/my',
                success: () => {
                  // 记录当前页面路径信息
                  this.updateRedirectInfo({
                    from: '/pages/cart/cart', // 从购物车页面来
                    openType: 'switchTab',
                  })
                }
              })
            }else{
              uni.showToast({
                title: `您未登录，将在：${this.seconds -i}秒跳转到登录页面`,
                duration: 1000,
                mask: true,
                icon: 'none'
              })
            }
          }, i*1000)
        }
      },
      // 支付下单
      async payOrder(){
        // 1 创建订单 2 获取支付参数 3 发起微信支付 4 确认钱到（公司）账
        // 准备参数
        const orderInfo = {
          // order_price: this.totalPrice,
          order_price: 0.01,
          consignee_addr: this.addstr,
          goods: this.cart.filter(item => item.goods_state)
                          .map(item => ({
                            goods_id: item.goods_id,
                            goods_number: item.goods_count,
                            goods_price: item.goods_price
                          }))
        }
        
        // 发起请求
        const {data: res} = await uni.$http.post('/my/orders/create', orderInfo)
        // 数据异常判断
        if(res.meta.status !== 200) return uni.$showMsg('创建订单失败')
        // 获取订单编号
        const orderNumber = res.message.order_number
        console.log('订单编号：', orderNumber)
        
        // 2 获取支付参数
        // 发起请求
        const {data: res2} = await uni.$http.post('/my/orders/req_unifiedorder', {order_number: orderNumber})
        // 数据异常判断
        if(res.meta.status !== 200) return uni.$showMsg('获取支付信息失败')
        // 获取支付参数
        const payInfo = res2.message.pay
        console.log('支付参数', payInfo)
        
        // 3 发起微信支付 
        const [err, succ] = await uni.requestPayment(payInfo)
        console.log('err', err, 'succ', succ)
        // 微信支付失败
        if (err) return uni.$showMsg('订单未支付！')
        
        // 4 确认钱到（公司）账
         const { data: res3 } = await uni.$http.post('/my/orders/chkOrder', { order_number: orderNumber })
         
         // 3.4 检测到订单未支付
         if (res3.meta.status !== 200) return uni.$showMsg('订单未支付！')
         
         //钱到账了
         uni.showToast({
           title: '支付完成！',
           icon: 'success'
         })
        
      }
    }
  }
</script>

<style lang="scss">
  .my-settle-container {
    /* 底部固定定位 */
    position: fixed;
    bottom: 0;
    left: 0;
    /* 设置宽高和背景色 */
    width: 100%;
    height: 50px;
    background-color: white; // 将背景色从 cyan 改为 white
    
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-left: 5px;
    font-size: 14px;
    
    z-index: 9;

    .radio {
      display: flex;
      align-items: center;
    }

    .amount-box {
      .amount {
        color: #c00000;
      }
    }

    .btn-settle {
      height: 50px;
      min-width: 100px;
      background-color: #c00000;
      color: white;
      line-height: 50px;
      text-align: center;
      padding: 0 10px;
    }
  }
</style>
